package com.lineage.server.datatables.sql;

import com.lineage.DatabaseFactory;
import com.lineage.server.datatables.CharObjidTable;
import com.lineage.server.datatables.storage.BadBuddyStorage;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BadBuddyTable implements BadBuddyStorage {
  private static final Log _log = LogFactory.getLog(BadBuddyTable.class);
  
  private static final Map<Integer, ArrayList<String>> _buddyMap = new HashMap<>();
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection co = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("SELECT * FROM `character_bad_buddy`");
      rs = ps.executeQuery();
      while (rs.next()) {
        int char_id = rs.getInt("char_id");
        if (CharObjidTable.get().isChar(char_id) != null) {
          int buddy_id = rs.getInt("buddy_id");
          if (CharObjidTable.get().isChar(buddy_id) != null) {
            String buddy_name = rs.getString("buddy_name");
            ArrayList<String> list = _buddyMap.get(Integer.valueOf(char_id));
            if (list == null) {
              ArrayList<String> newlist = new ArrayList<>();
              newlist.add(buddy_name);
              _buddyMap.put(Integer.valueOf(char_id), newlist);
              continue;
            } 
            list.add(buddy_name);
            continue;
          } 
          delete2(buddy_id);
          continue;
        } 
        delete(char_id);
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
    _log.info("载入黑名单录资料数量: " + _buddyMap.size() + "(" + timer.get() + "ms)");
  }
  
  private static void delete(int objid) {
    Connection cn = null;
    PreparedStatement ps = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("DELETE FROM `character_bad_buddy` WHERE `char_id`=?");
      ps.setInt(1, objid);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  private static void delete2(int buddy_id) {
    Connection cn = null;
    PreparedStatement ps = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("DELETE FROM `character_bad_buddy` WHERE `buddy_id`=?");
      ps.setInt(1, buddy_id);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  private static void addBuddyList(int objId, String skillTmp) {
    ArrayList<String> list = _buddyMap.get(Integer.valueOf(objId));
    if (list == null) {
      ArrayList<String> newlist = new ArrayList<>();
      newlist.add(skillTmp);
      _buddyMap.put(Integer.valueOf(objId), newlist);
    } else {
      list.add(skillTmp);
    } 
  }
  
  public ArrayList<String> getBuddyBadList(int playerobjid) {
    return _buddyMap.get(Integer.valueOf(playerobjid));
  }
  
  public void addBuddy(int charId, int objId, String name) {
    insertBuddyBad(charId, objId, name);
    ArrayList<String> list = _buddyMap.get(Integer.valueOf(charId));
    if (list == null) {
      ArrayList<String> newlist = new ArrayList<>();
      newlist.add(name);
      _buddyMap.put(Integer.valueOf(charId), newlist);
    } else {
      list.add(name);
    } 
  }
  
  public static void insertBuddyBad(int char_id, int buddy_id, String buddy_name) {
    Connection co = null;
    PreparedStatement ps = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("INSERT INTO `character_bad_buddy` SET `char_id`=?,`buddy_id`=?,`buddy_name`=?");
      ps.setInt(1, char_id);
      ps.setInt(2, buddy_id);
      ps.setString(3, buddy_name);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
      return;
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
  }
  
  public void removeBuddy(int charId, String buddyName) {
    ArrayList<String> list = _buddyMap.get(Integer.valueOf(charId));
    if (list != null) {
      list.remove(buddyName);
      Connection co = null;
      PreparedStatement ps = null;
      try {
        co = DatabaseFactory.get().getConnection();
        ps = co.prepareStatement("DELETE FROM `character_bad_buddy` WHERE `char_id`=? AND `buddy_name`=?");
        ps.setInt(1, charId);
        ps.setString(2, buddyName);
        ps.execute();
      } catch (SQLException e) {
        _log.error(e.getLocalizedMessage(), e);
        return;
      } finally {
        SQLUtil.close(ps);
        SQLUtil.close(co);
      } 
    } 
  }
  
  public boolean check(int charId, String name) {
    if (!_buddyMap.isEmpty()) {
      ArrayList<String> list = _buddyMap.get(Integer.valueOf(charId));
      if (list != null) {
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
          String s = iterator.next();
          if (s.equalsIgnoreCase(name))
            return true; 
        } 
      } 
    } 
    return false;
  }
}
